package com.nbsaas.boot.jobs;

import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.scheduling.api.apis.SchedulingTaskApi;
import com.nbsaas.boot.scheduling.api.apis.SchedulingTaskRecordApi;
import com.nbsaas.boot.scheduling.api.domain.request.SchedulingTaskRecordDataRequest;
import com.nbsaas.boot.scheduling.api.domain.response.SchedulingTaskResponse;
import com.nbsaas.boot.scheduling.data.entity.SchedulingTaskRecord;
import jodd.http.HttpRequest;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Date;


public class HttpJob implements Job {

    private Logger logger = LoggerFactory.getLogger("HttpJob");

    public void execute(JobExecutionContext context) {
        JobDataMap map = context.getJobDetail().getJobDataMap();
        String url = map.getString("url");
        logger.info("url:" + url);
        logger.info("time:" + new Date().toLocaleString());
        int state = 1;
        String body = "";
        if (url != null) {
            try {
                HttpRequest httpRequest = HttpRequest.get(url);
                httpRequest.send().charset("utf-8").bodyText();
                logger.info("执行完成");
                body = "ok";
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("执行失败");
                body = e.getMessage();
                state = 2;
            }
        } else {
            logger.info("url为空");
        }

        Object applicationContext = map.get("applicationContext");
        if (applicationContext == null) {
            return;
        }

        if (applicationContext instanceof ApplicationContext) {
            ApplicationContext beans = (ApplicationContext) applicationContext;
            SchedulingTaskRecordApi recordApi = beans.getBean(SchedulingTaskRecordApi.class);

            SchedulingTaskApi scheduleTaskApi = beans.getBean(SchedulingTaskApi.class);

            Long id = map.getLong("id");

            SchedulingTaskResponse task = scheduleTaskApi.oneData(Filter.eq("id", id));
            if (task == null) {
                return;
            }
            if (task.getRecordType() == null) {
                task.setRecordType(1);
            }
            if (task.getRecordType() == 2) {
                return;
            }

            SchedulingTaskRecordDataRequest form = new SchedulingTaskRecordDataRequest();
            form.setSchedulingTask(id);
            form.setState(state);
            form.setNote(body);
            recordApi.create(form);

        }

    }

}
